﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using System.Threading;

using TnToolTips;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.esriSystem;

namespace Tayninh2011
{
    public sealed partial class FrmCash : RootForm
    {
        #region Fields

        private delegate void TinhgiaDatDelegate();
        private TinhgiaDatDelegate TinhgiaDat;

        private List<string[]> lockStatus = new List<string[]>();
        private int flagLockStatus = 0;

        private DateTime dateTime=DateTime.Now;

        private Dictionary<EnumMainTask, List<EnumModeCalc>> mainTask = new Dictionary<EnumMainTask, List<EnumModeCalc>>();

        TnThua thua = null;
        TnDuong duong = null;
        TnHem hem = null;
        TnHem hem1 = null;
        TnDuong duong50 = null;
        TnDuong duong05 = null;
        TnDuong duong1 = null;

        private DataSet ds = new DataSet();
        private ITnExToolsDataManager toolData = new TnExToolsDataManager();
        private string dieukien = "";

        private TnCalculatorFactory calcFactory;
        private TnToolsCalculator calcTool;

        private int intSelectedRows = 0;

        TnToolTipsCustom toolTip = new TnToolTipsCustom();

        ITnMapController mapController = new TnMapController();
        private string table = "";

        //cho save du lieu
        object val = "";
        object id = "";
        string col = "";

        private string[] _strLayerNames = { "tn_duong", "tn_hem", "tn_thua" };
        private FrmTableNames frmTableName;
        private FrmAddSdeData frmAddSdeData;
        FrmLandpriceOnRoad frmLandPrice;
        //private List<string[]> RootForm.lstLayers = new List<string[]>();
        private EnumTypeOfLayer typeOfLayer = EnumTypeOfLayer.khac;
        private string strNameThua = "tn_thua";
        private string strNameDuong = "tn_duong";
        private string strNameHem = "tn_hem";
        private IToolbarMenu ContexMenuTOC = new ToolbarMenuClass();

        private ITnExcuteCalculator excutor = TnExcuteCalculator.CallMe;


        //public List<string[]> RootForm.lstLayers
        //{
        //    get { return RootForm.lstLayers; }
        //    set { RootForm.lstLayers = value; }
        //}

        #endregion Fields

        #region make it seleton

        private static readonly FrmCash meForm=new FrmCash();

        private FrmCash()
        {
            //MessageBox.Show("log 000");
            InitializeComponent();
            //MessageBox.Show("log 001");
            try
            {
                iniToolTips();
                //this.cbxChonLayer.SelectedIndex = 0;

                //iniMainTask();
                TinhgiaDat += initTask;
                tvcListLoaiThua.ExpandAll();

                tvcListLoaiThua.AfterCheck += tvcListLoaiThua_AfterCheckOrSelect;
                tvcListLoaiThua.AfterSelect += tvcListLoaiThua_AfterCheckOrSelect;

                tvcListLoaiThua.Nodes[0].Checked = true;
            }
            catch (Exception e) { MessageBox.Show(e.Message); }

            //ContexMenuTOC.AddItem("esriControls.ControlsMapZoomInTool", -1, -1, true, esriCommandStyles.esriCommandStyleIconAndText);
            //ContexMenuTOC.AddItem(new TnRemoveLayerCmd(), 1, 0, true, esriCommandStyles.esriCommandStyleIconAndText);

            //ContexMenuTOC.SetHook(axMapControl1);
            //tvcListLoaiThua.CheckAll();

            //bool odd = true;
            //Action<TreeNodeCollection> checkEverySecondLeaf = null;
            //checkEverySecondLeaf = Nodes =>
            //{
            //    foreach (TreeNode nd in Nodes)
            //    {
            //        if (nd.Nodes.Count == 0)
            //        {
            //            nd.Checked = odd;
            //            odd = !odd;
            //        }
            //        checkEverySecondLeaf(nd.Nodes);
            //    }
            //};
            //checkEverySecondLeaf(tvcListLoaiThua.Nodes);

            
            //ThuaPNNT.

        }
        private void iniToolTips()
        {
            
            toolTip.UseAnimation = true;
            
            toolTip.IsBalloon = true;
            toolTip.BorderColor = Color.Gray;
            toolTip.AutomaticDelay = 500;
            toolTip.AutoPopDelay = 3000;
            toolTip.ForeColor = Color.FromArgb(117,78,111);
           
            toolTip.ReshowDelay = 100;
            toolTip.SetToolTip(pbxThucHien, "Thực hiện các tác vụ");
            toolTip.SetToolTip(pbxRefresh, "Refresh");
            toolTip.SetToolTip(pbxMap, "Hiển thị cửa sổ bản đồ");
            toolTip.SetToolTip(pbxQuery, "Hiển thị dữ liệu");
            toolTip.SetToolTip(pbxSelectAll, "Chọn tất cả");
            toolTip.SetToolTip(pbxClearAll, "Bỏ chọn tất cả");
            toolTip.SetToolTip(tbxHelpInTasks, "Tình trạng tính toán");
            toolTip.SetToolTip(pbxClearTvc, "Bỏ chọn hết");
            toolTip.SetToolTip(pbxApGia, "Áp Giá");
            toolTip.SetToolTip(pbxLockStatus, "Khóa/mở khóa quyền cập nhật cho đối tượng");
            toolTip.SetToolTip(pbxSave, "Lưu dữ liệu");
            toolTip.SetToolTip(pbxErrorUpdate, "Lỗi cập nhật dữ liệu lúc: ");
            toolTip.SetToolTip(pbxOkUpdate, "Đã lưu dữ liệu");
            
            
        }

        private void iniMainTask()
        {
            throw new NotImplementedException();
        }
        private void tvcListLoaiThua_AfterCheckOrSelect(object sender, TreeViewEventArgs e)
        {
            var tv = (TnControlLib.TnTreeViewCheckBox)sender;
            string a = "";
            //nodesName = tvcListLoaiThua.walkOnTreeGetChecked();
            var nd = tv.SelectedNode;
            //MessageBox.Show("L");
            if (nd == null) return;
            foreach (string b in tvcListLoaiThua.ListNodeChecked)
            {
                a += b + " ";
            }
            //MessageBox.Show(a);

            tbxCachTinh.Text = string.Concat(nd.Text, ": Checkstate.", tv.GetState(nd), ", Checked=", nd.Checked);
        }

        
        private List<string> nodesName = new List<string>();
        

        public static FrmCash CallMe
        {
            get { return meForm; }
        }

        public new void Show()
        {
            if (isShown)
            {
                base.Show();
            }
            else
            {
                base.Show();
                isShown = true;
            }
        }
        private static bool isShown = false;
        static FrmCash()
        {

            meForm.FormClosing += new FormClosingEventHandler(meForm_FormClosing);

        }
        private static void meForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            isShown = false;
            //formMain2.Hide();
            Application.ExitThread();
            Application.Exit();
        }
        #endregion Seleton
        private void initListThuaTree()
        {
            //Thửa chọn
            //Thửa PNNDT
            //--Thửa Mặt tiền (vt1)
            //--Thửa Sau 50m
            //--Thửa hẻm
            //----Hẻm chính
            //----Hẻm phụ
            //Thửa PNNT
            //--Đất ở
            //--Đất PN khác
            //Thửa NN
            //--Bình thường
            //--Đặc biệt

        }
        public ESRI.ArcGIS.Controls.AxMapControl GetMapControl()
        {
            return this.axMapControl1;
        }
        public ESRI.ArcGIS.Controls.AxTOCControl GetTocControl()
        {
            return this.axTOCControl1;
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void tvcListLoaiThua_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            tvcListLoaiThua.CheckAll();
        }

        private void btnClearTvc_Click(object sender, EventArgs e)
        {
            tvcListLoaiThua.UncheckedAll();
        }

        private void rbtAllThua_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtAllThua.Checked)
            {
                tvcListLoaiThua.Enabled = true;
                pbxClearTvc.Enabled = true;
            }
        }

        private void rbtSelectedThua_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtSelectedThua.Checked)
            {
                tvcListLoaiThua.Enabled = false;
                pbxClearTvc.Enabled = false;
            }
        }

        //private void btnThucHien_Click(object sender, EventArgs e)
        //{
        //    btnThucHien.Enabled = false;
        //    this.pbrThucHien.Visible = true;
            
        //    tinh();
        //}
        private void tinh()
        {
            Delegate[] list;
            reMoveAllTask(ref TinhgiaDat);
            

            //xet cac task duoc check
            int i=0;
            while (i < tvcListLoaiThua.ListNodeChecked.Count)
            {
                if (tvcListLoaiThua.ListNodeChecked[i] == EnumMainTask.Task30xx.ToString())
                {
                    if (i + 1 < tvcListLoaiThua.ListNodeChecked.Count)
                    {
                        if (tvcListLoaiThua.ListNodeChecked[i + 1] == EnumMainTask.Task31xx.ToString())
                        {
                            //reMoveAllTask(ref TinhgiaDat);
                            //addTask(tinhThuaMattienThenThuaHem);

                            excutor.RemoveAll();
                            excutor.AddTask(TnExcuteCalcType.THUA_MAT_TIEN_VA_HEM);
                        }
                    }
                    else
                    {
                        //addTask(tinhThuaMattien);
                        excutor.AddTask(TnExcuteCalcType.THUA_MAT_TIEN);
                    }
                    //addTask(tinhThuaSau50m);
                }
                if (i ==0 && tvcListLoaiThua.ListNodeChecked[i] == EnumMainTask.Task31xx.ToString())
                {
                    //addTask(tinhThuaHem);

                    excutor.AddTask(TnExcuteCalcType.THUA_HEM);
                }
                
                i++;
            }
            //list = TinhgiaDat.GetInvocationList();
            //foreach (Delegate a in list)
            //{
            //    MessageBox.Show(a.Method.Name);
            //}
            //TinhgiaDat();
            excutor.CalcTool3010.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(calculating);
            excutor.CalcTool3020.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(calculating);
            excutor.CalcTool31xx32xx.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(calculating);

            excutor.CalcTool31xx32xx.BackgroundWorker.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
            //MessageBox.Show(RootForm._sdeEnvironment);
            excutor.Start();
            //excutor.CalcTool.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(calculating);
            
            
            //if (excutor.IsFinished)
            //{
            //    this.actionComplete();
            //}
        }
        //
        //ko su dung
        //
        #region Chi tinh thua mat tien

        //private void tinhThuaMattien()
        //{
        //    calcFactory = TnCalculatorFactory.CallMe;// new TnCalculatorFactory(RootForm._sdeWorkspace, RootForm._sdeEnvironment, RootForm._arrUserInfo);
        //    calcFactory.SetParams(RootForm.SdeWorkspace, RootForm.SdeEnvironment, RootForm.UserInfo);
        //    this.tbxHelpInTasks.Text = "Đang tính cho thửa mặt tiền";
        //    ITnToolsWorkspace toolWsp = new TnTools();
        //    ITnToolsTable toolTbl = new TnTools();
        //    toolTbl.TnFormatTable(RootForm._sdeWorkspace, strNameThua);
        //    //MessageBox.Show("ok");
        //    TnThuaFactory thuaFactory = new TnThuaFactory();
        //    TnDuongFactory duongFactory = new TnDuongFactory();
        //    toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameThua, TnToolsCalculator.fcachtinh, "");
        //    thua = thuaFactory.GetThua("3010", RootForm._sdeWorkspace);
        //    //duong = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1, this._sdeWorkspace);
        //    duong50 = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1_buff_50, RootForm._sdeWorkspace);

        //    duong05 = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1_buff_05, RootForm._sdeWorkspace);
 
        //    calcTool = calcFactory.GetCalculator(EnumModeCalc.mode3010);
        //    calcTool.AddExTool(EnumExTools.spatialRelTool);
        //    calcTool.ClearInputValues();
        //    calcTool.SetInputValues(ref thua, ref duong05, EnumTask.addInfo3010);
        //    calcTool.SetInputValues(ref thua, ref duong50, EnumTask.landPrice3010);
        //    calcTool.AddTask(EnumTask.addInfo3010);
        //    calcTool.AddTask(EnumTask.landPrice3010);
        //    calcTool.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
        //    calcTool.BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(continueTinhThuaSau50m);
        //    calcTool.Start();
        //}

        //private void tinhThuaSau50m()
        //{
        //    calcFactory = TnCalculatorFactory.CallMe;// new TnCalculatorFactory(RootForm._sdeWorkspace, RootForm._sdeEnvironment, RootForm._arrUserInfo);
        //    calcFactory.SetParams(RootForm.SdeWorkspace, RootForm.SdeEnvironment, RootForm.UserInfo);
        //    this.tbxHelpInTasks.Text = "Đang tính cho các thửa có đất sau mặt tiền 50m";
        //    calcTool = calcFactory.GetCalculator(EnumModeCalc.mode3020);
        //    //MessageBox.Show(calcTool.Name);
        //    calcTool.AddExTool(EnumExTools.dataManager, EnumExTools.spatialRelTool, EnumExTools.spatialTool);
        //    calcTool.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
        //    calcTool.BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
        //    //thua.FeatureCursor = thua.FeatureClass.Search(null, false);
        //    duong50.FeatureCursor = duong50.FeatureClass.Search(null, false);
        //    duong50.Feature = duong50.FeatureCursor.NextFeature();

        //    calcTool.ClearInputValues();
        //    calcTool.SetInputValues(ref thua, ref duong50, EnumTask.landPrice3020);

        //    calcTool.AddTask(EnumTask.landPrice3020);

        //    string[] a = calcTool.ListTasks();
        //    //MessageBox.Show(a.Length.ToString()+","+a[0]+","+a[1]);
        //    calcTool.Start();
        //}

        #endregion Chi tinh thua mat tien

        #region Tinh thua mat tien sau do tinh thua hem

        //private void tinhThuaMattienThenThuaHem()
        //{
        //    calcFactory = TnCalculatorFactory.CallMe;// new TnCalculatorFactory(RootForm._sdeWorkspace, RootForm._sdeEnvironment, RootForm._arrUserInfo);
        //    calcFactory.SetParams(RootForm.SdeWorkspace, RootForm.SdeEnvironment, RootForm.UserInfo);
        //    this.tbxHelpInTasks.Text = "Đang tính cho thửa mặt tiền";
        //    ITnToolsWorkspace toolWsp = new TnTools();
        //    ITnToolsTable toolTbl = new TnTools();
        //    toolTbl.TnFormatTable(RootForm._sdeWorkspace, strNameThua);
        //    //MessageBox.Show("ok");
        //    TnThuaFactory thuaFactory = new TnThuaFactory();
        //    TnDuongFactory duongFactory = new TnDuongFactory();
        //    thua = thuaFactory.GetThua("3010", RootForm._sdeWorkspace);
        //    //duong = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1, this._sdeWorkspace);
        //    duong50 = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1_buff_50, RootForm._sdeWorkspace);

        //    duong05 = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1_buff_05, RootForm._sdeWorkspace);

        //    calcTool = calcFactory.GetCalculator(EnumModeCalc.mode3010);
        //    calcTool.AddExTool(EnumExTools.spatialRelTool);
        //    calcTool.ClearInputValues();
        //    calcTool.SetInputValues(ref thua, ref duong05, EnumTask.addInfo3010);
        //    calcTool.SetInputValues(ref thua, ref duong50, EnumTask.landPrice3010);
        //    calcTool.AddTask(EnumTask.addInfo3010);
        //    calcTool.AddTask(EnumTask.landPrice3010);
        //    calcTool.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
        //    calcTool.BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(continueTinhThuaSau50m2);
        //    calcTool.Start();
        //}

        //private void tinhThuaSau50mThenThuaHem()
        //{
        //    calcFactory = TnCalculatorFactory.CallMe;// new TnCalculatorFactory(RootForm._sdeWorkspace, RootForm._sdeEnvironment, RootForm._arrUserInfo);
        //    calcFactory.SetParams(RootForm.SdeWorkspace, RootForm.SdeEnvironment, RootForm.UserInfo);
        //    this.tbxHelpInTasks.Text = "Đang tính cho các thửa có đất sau mặt tiền 50m";
        //    calcTool = calcFactory.GetCalculator(EnumModeCalc.mode3020);
        //    //MessageBox.Show(calcTool.Name);
        //    calcTool.AddExTool(EnumExTools.dataManager, EnumExTools.spatialRelTool, EnumExTools.spatialTool);
        //    calcTool.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
        //    calcTool.BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(continueTinhThuaHem);
        //    //thua.FeatureCursor = thua.FeatureClass.Search(null, false);
        //    duong50.FeatureCursor = duong50.FeatureClass.Search(null, false);
        //    duong50.Feature = duong50.FeatureCursor.NextFeature();

        //    calcTool.ClearInputValues();
        //    calcTool.SetInputValues(ref thua, ref duong50, EnumTask.landPrice3020);

        //    calcTool.AddTask(EnumTask.landPrice3020);

        //    string[] a = calcTool.ListTasks();
        //    //MessageBox.Show(a.Length.ToString()+","+a[0]+","+a[1]);
        //    calcTool.Start();
        //}

        //private void tinhThuaHem()
        //{
        //    calcFactory = TnCalculatorFactory.CallMe;// new TnCalculatorFactory(RootForm._sdeWorkspace, RootForm._sdeEnvironment, RootForm._arrUserInfo);
        //    calcFactory.SetParams(RootForm.SdeWorkspace, RootForm.SdeEnvironment, RootForm.UserInfo);
        //    this.tbxHelpInTasks.Text = "Đang tính cho thửa hẻm";
        //    ITnToolsWorkspace toolWsp = new TnTools();
        //    ITnToolsTable toolTbl = new TnTools();
        //    TnThuaFactory thuaFactory = new TnThuaFactory();
        //    TnDuongFactory duongFactory = new TnDuongFactory();
        //    TnHemFactory hemFactory = new TnHemFactory();

        //    toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameHem, TnToolsCalculator.fghichuhem, "");
        //    //toolTbl.TnFormatColumn(RootForm._sdeWorkspace, "tn_hem", "soduongchinh", 0);
        //    toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameHem, TnToolsCalculator.fgiadathem, 0);
        //    toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameHem, TnToolsCalculator.fsodgc, 0);
        //    toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameHem, TnToolsCalculator.fhemchinh, -1);
        //    toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameHem, TnToolsCalculator.fsohmc, 0);
        //    toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameHem, TnToolsCalculator.ftenhmc, "");
        //    toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameHem, TnToolsCalculator.ftendgc, "");
        //    toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameThua, TnToolsCalculator.fsomathem, 0);
        //    //toolTbl.TnFormatColumn(RootForm._sdeWorkspace, strNameThua, TnToolsCalculator.fcachtinh, "");

        //    thua = thuaFactory.GetThua("3010", RootForm._sdeWorkspace);//gia tri 3010 ko co y nghia
        //    duong1 = duongFactory.GetDuong(EnumLoaiDuong.dp_loai1_buff_1, RootForm._sdeWorkspace);
        //    hem = hemFactory.GetHem(EnumLoaiHem.hemDuongPho, RootForm._sdeWorkspace, RootForm._sdeEnvironment, RootForm._arrUserInfo);

        //    //hem1=hemFactory.GetHem(EnumLoaiHem.hemBuffer1m,this._sdeWorkspace,this._sdeEnvironment);

        //    calcTool = calcFactory.GetCalculator(EnumModeCalc.mode31xxAnd32xx);
        //    calcTool.AddExTool(EnumExTools.dataManager, EnumExTools.spatialRelTool, EnumExTools.spatialTool);
        //    calcTool.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
        //    calcTool.BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
        //    //duong1.FeatureCursor = duong1.FeatureClass.Search(null, false);

        //    calcTool.ClearInputValues();
        //    calcTool.SetInputValues(ref thua, ref duong1, ref hem, EnumTask.addInfoHemChinh);
        //    calcTool.SetInputValues(ref thua, ref duong1, ref hem, EnumTask.addInfoHemPhu);
        //    calcTool.SetInputValues(ref thua, EnumTask.addInfo31xx);
        //    calcTool.SetInputValues(ref thua, EnumTask.addInfo32xx);

        //    calcTool.AddTask(EnumTask.addInfoHemChinh);
        //    calcTool.AddTask(EnumTask.addInfoHemPhu);
        //    calcTool.AddTask(EnumTask.addInfo31xx);
        //    calcTool.AddTask(EnumTask.addInfo32xx);

        //    calcTool.Start();
        //}
        #endregion Tinh thua mat tien sau do tinh thua hem
        //

        private void tinhThuaSau50mOnly()
        {
            //MessageBox.Show("sau 50 m only");
        }


        
        #region BackgroundWorker Handler
        void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
            //btnThucHien.Enabled = true;
            pbxThucHien.Enabled = true;
            pbxThucHien.Image= global::Tayninh2011.Properties.Resources.TnCalculator_40_54;
            pbxQuery.Image = global::Tayninh2011.Properties.Resources.query;
            pbxQuery.Enabled = true;
            this.pbrThucHien.Value = 0;
            this.pbrThucHien.Visible = false;
            
            this.tbxHelpInTasks.Text = "";
            MessageBox.Show("Đã tính xong");
        }
        //void continueTinhThuaSau50m(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    tinhThuaSau50m();
        //}
        //void continueTinhThuaSau50m2(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    tinhThuaSau50mThenThuaHem();
        //}
        //void continueTinhThuaHem(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    tinhThuaHem();
        //}
        void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.pbrThucHien.Value = e.ProgressPercentage;
            
            this.Cursor = Cursors.AppStarting;
            
            //this.label1.Text = e.ProgressPercentage.ToString() + "%";
        }
        #endregion BackgroundWorker Handler

        private void addTask(TinhgiaDatDelegate task)
        {
            Delegate[] dele; 
            dele=TinhgiaDat.GetInvocationList();
            foreach (TinhgiaDatDelegate d in dele)
            {
                if (d.Method.Name == task.Method.Name)
                {
                    MessageBox.Show(d.Method.Name +" "+ task.Method.Name);
                    return;
                }
            }
            TinhgiaDat += task;
        }
        private void reMoveAllTask(ref TinhgiaDatDelegate delTasks)
        {
            Delegate[] dele;
            dele = delTasks.GetInvocationList();
            foreach (TinhgiaDatDelegate task in dele)
            {
                delTasks -= task;
            }
            delTasks += initTask;

        }

        //dung de boi tron delegate
        private void initTask() {}
        //

        private void button1_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(RootForm._sdeEnvironment);
            axMapControl1.Map.MoveLayer(axMapControl1.Map.get_Layer(0), 1);
        }

        private void cbxChonLayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            //cbxChonLayer.Enabled = false;
            string[] t = cbxChonLayer.Text.Split('.');
            table = t.GetValue(t.Length - 1).ToString();
            //MessageBox.Show(RootForm._lstLayers[0].GetValue(0).ToString());
            for (int i = 0; i < RootForm._lstLayers.Count; i++)
            {
                if (String.Compare(table, RootForm._lstLayers[i].GetValue(1).ToString(), true) == 0)
                {
                    switch (RootForm._lstLayers[i].GetValue(0).ToString())
                    {
                        case "thua":
                            this.typeOfLayer = EnumTypeOfLayer.thua;
                            cbxLoaiDat.Enabled = true;
                            cbxChonTheoDuong.Enabled = true;
                            cbxChonTheoHuyen.Enabled = true;
                            break;
                        case "duong":
                            this.typeOfLayer = EnumTypeOfLayer.duong;
                            cbxLoaiDat.Enabled = false;
                            cbxChonTheoDuong.Enabled = false;
                            cbxChonTheoHuyen.Enabled = false;
                            break;
                        case "hem":
                            this.typeOfLayer = EnumTypeOfLayer.hem;
                            cbxLoaiDat.Enabled = false;
                            cbxChonTheoDuong.Enabled = false;
                            cbxChonTheoHuyen.Enabled = false;
                            break;
                        case "thua_giadat":
                            this.typeOfLayer = EnumTypeOfLayer.thuaGiadat;
                            cbxLoaiDat.Enabled = false;
                            cbxChonTheoDuong.Enabled = false;
                            cbxChonTheoHuyen.Enabled = false;
                            break;
                        default:
                            this.typeOfLayer = EnumTypeOfLayer.khac;
                            cbxLoaiDat.Enabled = false;
                            cbxChonTheoDuong.Enabled = false;
                            cbxChonTheoHuyen.Enabled = false;
                            break;
                    }
                }
            }
            //if (cbxChonLayer.Text == "Thửa")
            //{
            //    cbxLoaiDat.Enabled = true;
            //    cbxChonTheoDuong.Enabled = true;
            //    cbxChonTheoHuyen.Enabled = true;
                
            //    table = "tn_thua";
            //}
            //else
            //{
            //    cbxLoaiDat.Enabled = false;
            //    cbxChonTheoDuong.Enabled = false;
            //    cbxChonTheoHuyen.Enabled = false;
            //    if (cbxChonLayer.Text == "Đường giao thông")
            //    {
                    
            //        table = "tn_duong";
            //    }
            //    else
            //    {
                    
            //        table = "tn_hem";
            //    }
            //}
            showData(cbxChonLayer.Text);
            //bwShowData.RunWorkerAsync();
        }
        private void showData(string table)
        {
            
            dieukien="select * from "+table;
            //switch (table)
            //{
            //    case "Thửa":
            //        dieukien = "select * from tn_thua";
            //        break;
            //    case "Đường giao thông":
            //        dieukien = "select * from tn_duong";
            //        break;
            //    case "Hẻm":
            //        dieukien = "select * from tn_hem";
            //        break;
            //    default: break;
            //}
            
        }
        private void dgvTable_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvTable_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                updateSelectedRowsNumber();
                tvCachTinh.Nodes.Clear();
                mapController.SelectFeature(table, dieukienChonFeature(), ref axMapControl1);
                //MessageBox.Show(table);
                if (typeOfLayer == EnumTypeOfLayer.thua)
                {
                    int indexGhichu = dgvTable.Columns["ghichu"].Index;
                    int indexCachtinh = dgvTable.Columns["cachtinh"].Index;
                    int indexSomattien = dgvTable.Columns["somattien"].Index;
                    List<TreeNode> nodes = new List<TreeNode>();
                    if (e.RowIndex != -1)
                    {
                        string ghichu = dgvTable.Rows[e.RowIndex].Cells[indexGhichu].Value.ToString();
                        string cachtinh = dgvTable.Rows[e.RowIndex].Cells[indexCachtinh].Value.ToString();
                        string somattien = dgvTable.Rows[e.RowIndex].Cells[indexSomattien].Value.ToString();
                        if (!ghichu.Equals(" "))
                        {
                            string[] arrGhichu = ghichu.Split(',');
                            string[] arrCachtinh = cachtinh.Split(',');
                            List<string[]> arrDetailGhichu = new List<string[]>();
                            string[] detailGhichu;

                            int intCachtinh = arrGhichu.Length;
                            for (int i = 0; i < intCachtinh; i++)
                            {
                                detailGhichu = arrGhichu[i].Split('-');
                                arrDetailGhichu.Add(detailGhichu);
                            }
                            //tbxCachTinh.Text = ghichu;

                            TreeNode rootGiaothongNode = new TreeNode("Mặt tiền");
                            tvCachTinh.Nodes.Add(rootGiaothongNode);
                            //1-somattien 2-maduong 3-tenduong 4-cachtinh
                            for (int i = 0; i < intCachtinh; i++)
                            {
                                nodes.Add(new TreeNode(arrDetailGhichu[i][2]));//tenduong
                                nodes[i].Tag = arrCachtinh.GetValue(i);
                                rootGiaothongNode.Nodes.Add(nodes[i]);

                            }
                            tvCachTinh.ExpandAll();
                        }
                        else
                        {
                            //MessageBox.Show("chua co cach tinh");
                        }
                    }
                    else
                    { //MessageBox.Show("a"); 

                    }
                }
            }
            catch { }
            //tvCachTinh.Nodes.Add
        }

        private void btnMap_Click(object sender, EventArgs e)
        {
            FrmMap frmMam = FrmMap.FormMap;
            frmMam.Show();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (cbxChonLayer.Text == "")
            {
                return;
            }
            else
            {
                cbxChonLayer.Enabled = false;
                showData(cbxChonLayer.Text);
                bwShowData.RunWorkerAsync();
            }
        }

        private void bwShowData_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ds = toolData.TnQueryBySQL(RootForm._arrUserInfo, dieukien);
                
            }
            catch { }
        }

        private void bwShowData_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            cbxChonLayer.Enabled = true;
            this.dgvTable.DataSource = ds.Tables[0];
            this.dgvTable.Columns["ghichu"].Visible = false;
            this.dgvTable.Columns["objectid"].Visible = false;
            this.dgvTable.Columns["shape"].Visible = false;
            lblSelected.Text = "0";
            updateSelectedRowsNumber();
            lblSum.Text=string.Format("/ {0}", ds.Tables[0].Rows.Count.ToString());
        }
        private void updateSelectedRowsNumber()
        {
            intSelectedRows = dgvTable.SelectedRows.Count;
            lblSelected.Text = intSelectedRows.ToString();
            //MessageBox.Show(intSelectedRows.ToString());
        }
        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            dgvTable.SelectAll();
            updateSelectedRowsNumber();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            dgvTable.ClearSelection();
            updateSelectedRowsNumber();
        }

        private void dgvTable_MouseUp(object sender, MouseEventArgs e)
        {
            updateSelectedRowsNumber();
            this.dgvTable.ContextMenu = new ContextMenu();
            MenuItem zoom = new MenuItem();
            zoom.Text = "&Xem bản đồ";
            this.dgvTable.ContextMenu.MenuItems.Add(zoom);
            if (dgvTable.SelectedRows.Count != 0 && e.Button==MouseButtons.Right)
            {
                this.dgvTable.ContextMenu.Show(dgvTable, new Point(e.X, e.Y));
            }
            zoom.Click += new EventHandler(zoom_Click);

            //gan gia tri lock
            if (this.typeOfLayer == EnumTypeOfLayer.thua)
            {
                try
                {
                    int indexOfLock = dgvTable.Columns["kdat"].Index;
                    int indexOfObjectId = dgvTable.Columns["objectid"].Index;
                    string lck = "";
                    string id = "";
                    lockStatus.Clear();
                    for (int i = 0; i < dgvTable.SelectedRows.Count; i++)
                    {
                        lck = dgvTable.Rows[dgvTable.SelectedRows[i].Index].Cells[indexOfLock].Value.ToString();
                        id = dgvTable.Rows[dgvTable.SelectedRows[i].Index].Cells[indexOfObjectId].Value.ToString();
                        //MessageBox.Show(dk);
                        lockStatus.Add(new string[] { id, lck });
                    }
                    if (lockStatus[0][1] == "3010")
                    {
                        flagLockStatus = 0;
                        pbxLockStatus.Image = global::Tayninh2011.Properties.Resources.TnUnlocked;
                    }
                    else
                    {
                        flagLockStatus = 1;
                        pbxLockStatus.Image = global::Tayninh2011.Properties.Resources.TnLocked;
                    }
                }
                catch { }
            }
        }

        void zoom_Click(object sender, EventArgs e)
        {
            ZoomToSelected_Click(sender, e);
        }

        private void cbxLoaiDat_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbxLoaiDat.Text)
            {
                case "Đất ở đô thị":
                    dieukien = "select * from "+table+" where loaidat='ODT'";
                    break;
                default: break;
            }
            //showData(cbxChonLayer.Text);
            //bwShowData.RunWorkerAsync();
        }

        private void dgvTable_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            
        }

        private void ZoomToSelected_Click(object sender, EventArgs e)
        {
            if (dgvTable.SelectedRows.Count == 0)
            {
                return;
            }
            FrmMap frmMap = FrmMap.FormMap;
            string dk = "";
            dk = dieukienChonFeature();
            
            //switch (cbxChonLayer.Text)
            //{
            //    case "Thửa":
            //        table = "sde.SDE.tn_thua";
            //        break;
            //    case "Đường giao thông":
            //        table = "sde.SDE.tn_duong";
            //        break;
            //    case "Hẻm":
            //        table = "sde.SDE.tn_hem";
            //        break;
            //    default: break;
            //}
            //frmMap.ZoomToSelected(table,dk);
            //ITnMapController mapController = new TnMapController();
            mapController.ZoomToSelected(table, dk, ref this.axMapControl1);

        }

        private string dieukienChonFeature()
        {
            string dk = "";
            List<string> listDk = new List<string>();
            int indexOfObjectid = dgvTable.Columns["objectid"].Index;
            for (int i = 0; i < dgvTable.SelectedRows.Count; i++)
            {
                dk = "objectid=" + dgvTable.Rows[dgvTable.SelectedRows[i].Index].Cells[indexOfObjectid].Value.ToString();
                //MessageBox.Show(dk);
                listDk.Add(dk);
            }
            dk = "";
            for (int i = 0; i < listDk.Count; i++)
            {
                if (i != listDk.Count - 1)
                {
                    dk += listDk[i] + " or ";
                }
                else
                {
                    dk += listDk[i];
                }
            }
            return dk;
        }

        private void pbxRefresh_Click(object sender, EventArgs e)
        {
            if (cbxChonLayer.Text == "")
            {
                return;
            }
            else
            {
                cbxChonLayer.Enabled = false;
                showData(cbxChonLayer.Text);
                bwShowData.RunWorkerAsync();
            }
        }

        private void pbxMap_Click(object sender, EventArgs e)
        {
            FrmMap frmMap = FrmMap.FormMap;
            frmMap.Show();
            
        }

        private void pbxThucHien_Click(object sender, EventArgs e)
        {
            //btnThucHien.Enabled = false;
            if (tvcListLoaiThua.ListNodeChecked.Count != 0)
            {
                this.strNameThua = RootForm.GetLayers.GetValue(0).ToString();
                this.strNameDuong = RootForm.GetLayers.GetValue(1).ToString();
                this.strNameHem = RootForm.GetLayers.GetValue(2).ToString();
                pbxThucHien.Enabled = false;
                pbxThucHien.Image = global::Tayninh2011.Properties.Resources.TnCalculating_40_54;
                this.pbrThucHien.Visible = true;
                pbxQuery.Image = global::Tayninh2011.Properties.Resources.TnQuering;
                pbxQuery.Enabled = false;
                tinh();
            }
            else
            {
                return;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
        }

        private void pbxQuery_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(RootForm.lstLayers[0].GetValue(1).ToString());
            //cbxChonLayer.Enabled = false;
            for (int i = 0; i < RootForm._lstLayers.Count; i++)
            {
                if (String.Compare(table, RootForm._lstLayers[i].GetValue(1).ToString(), true) == 0)
                {
                    switch (RootForm._lstLayers[i].GetValue(0).ToString())
                    {
                        case "thua":
                            this.typeOfLayer = EnumTypeOfLayer.thua;

                            break;
                        case "duong":
                            this.typeOfLayer = EnumTypeOfLayer.duong;

                            break;
                        case "hem":
                            this.typeOfLayer = EnumTypeOfLayer.hem;

                            break;
                        case "thua_giadat":
                            this.typeOfLayer = EnumTypeOfLayer.thuaGiadat;

                            break;
                        default:
                            this.typeOfLayer = EnumTypeOfLayer.khac;

                            break;
                    }
                }
            }
            try
            {
                showData(cbxChonLayer.Text);
            }
            catch { }
            if (cbxChonLayer.Enabled)
            {
                switch (cbxLoaiDat.Text)
                {
                    case "Đất ở đô thị":
                        dieukien = "select * from "+cbxChonLayer.Text+" where loaidat='ODT'";
                        break;
                    default: break;
                }
            }

            bwShowData.RunWorkerAsync();
        }

        private void pbxSelectAll_Click(object sender, EventArgs e)
        {
            dgvTable.SelectAll();
            updateSelectedRowsNumber();
        }

        private void pbxClearAll_Click(object sender, EventArgs e)
        {
            dgvTable.ClearSelection();
            updateSelectedRowsNumber();
        }

        private void pbxLock_Click(object sender, EventArgs e)
        {
            lockIt();
        }

        private void lockIt()
        {
            if (flagLockStatus==0)
            {
                pbxLockStatus.Image = global::Tayninh2011.Properties.Resources.TnLocked;
                flagLockStatus = 1;
            }
            else
            {
                pbxLockStatus.Image = global::Tayninh2011.Properties.Resources.TnUnlocked;
                flagLockStatus = 0;
            }
        }

        private void pbxClearTvc_Click(object sender, EventArgs e)
        {
            tvcListLoaiThua.UncheckedAll();
        }

        #region Save Data
        private void dgvTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show("edit");
            pbxSave.Visible = false;
            if (e.RowIndex != -1 && e.RowIndex != e.RowIndex - 1)
            {
                
                val = dgvTable.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                col = dgvTable.Columns[e.ColumnIndex].Name.ToString();
                int indexOfObjectId = dgvTable.Columns["objectid"].Index;
                id = dgvTable.Rows[e.RowIndex].Cells[indexOfObjectId].Value;
                saveData(col, id, val);
            }
        }

        private void saveData(string column,object id,object value)
        {
            string sql = "update " + table + " set ";
            sql += column + " = " + "N'" + val + "'";
            sql += " where objectid = " + "N'" + id + "'";
            if (toolData.TnUpdateBySQL(RootForm._arrUserInfo, sql))
            {
                pbxOkUpdate.Visible = true;
                pbxErrorUpdate.Visible = false;
                
            }
            else
            {
                pbxOkUpdate.Visible = false;
                pbxErrorUpdate.Visible = true;
            }
            dateTime = DateTime.Now;
            lbl6.Visible = true;
            lblTimeNow.Text = dateTime.Hour.ToString() + ":" + dateTime.Minute.ToString() + ":" + dateTime.Second.ToString();
        }

        private void pbxSave_Click(object sender, EventArgs e)
        {
            saveData(col,id,val);
        }

        private void dgvTable_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            //MessageBox.Show("begin");
            pbxSave.Visible = true;
        }
        #endregion

        private void pbxErrorUpdate_Click(object sender, EventArgs e)
        {

        }

        #region Hover image

        private void pbxApGia_MouseHover(object sender, EventArgs e)
        {
            pbxApGia.Image = global::Tayninh2011.Properties.Resources.TnOk_hover;
        }

        private void pbxLockStatus_MouseHover(object sender, EventArgs e)
        {
            if (flagLockStatus == 0)
            {
                pbxLockStatus.Image = global::Tayninh2011.Properties.Resources.TnUnlocked_hover;
            }
            else
            {
                pbxLockStatus.Image = global::Tayninh2011.Properties.Resources.TnLocked_hover;
            }
        }

        private void pbxMap_MouseHover(object sender, EventArgs e)
        {
            pbxMap.Image = global::Tayninh2011.Properties.Resources.TnMap_hover;
        }

        private void pbxMap_MouseLeave(object sender, EventArgs e)
        {
            pbxMap.Image = global::Tayninh2011.Properties.Resources.TnMap;
        }

        private void pbxLockStatus_MouseLeave(object sender, EventArgs e)
        {
            if (flagLockStatus == 0)
            {
                pbxLockStatus.Image = global::Tayninh2011.Properties.Resources.TnUnlocked;
            }
            else
            {
                pbxLockStatus.Image = global::Tayninh2011.Properties.Resources.TnLocked;
            }
        }

        private void pbxApGia_MouseLeave(object sender, EventArgs e)
        {
            pbxApGia.Image = global::Tayninh2011.Properties.Resources.TnOk;
        }

        private void pbxClearTvc_MouseHover(object sender, EventArgs e)
        {
            pbxClearTvc.Image = global::Tayninh2011.Properties.Resources.TnClearSelected_hover;
        }

        private void pbxClearTvc_MouseLeave(object sender, EventArgs e)
        {
            pbxClearTvc.Image = global::Tayninh2011.Properties.Resources.TnClearSelected;
        }

        private void pbxSelectAll_MouseHover(object sender, EventArgs e)
        {
            pbxSelectAll.Image = global::Tayninh2011.Properties.Resources.TnSelectAll_hover;
        }

        private void pbxSelectAll_MouseLeave(object sender, EventArgs e)
        {
            pbxSelectAll.Image = global::Tayninh2011.Properties.Resources.TnSelectAll;
        }

        private void pbxClearAll_MouseHover(object sender, EventArgs e)
        {
            pbxClearAll.Image = global::Tayninh2011.Properties.Resources.TnClearSelected_hover;
        }

        private void pbxClearAll_MouseLeave(object sender, EventArgs e)
        {
            pbxClearAll.Image = global::Tayninh2011.Properties.Resources.TnClearSelected;
        }

        private void pbxQuery_MouseHover(object sender, EventArgs e)
        {
            pbxQuery.Image = global::Tayninh2011.Properties.Resources.TnQuery_hover;
        }

        private void pbxQuery_MouseLeave(object sender, EventArgs e)
        {
            pbxQuery.Image = global::Tayninh2011.Properties.Resources.query;
        }

        private void pbxSave_MouseHover(object sender, EventArgs e)
        {
            pbxSave.Image = global::Tayninh2011.Properties.Resources.TnSave_28_28_hover;
        }

        private void pbxSave_MouseLeave(object sender, EventArgs e)
        {
            pbxSave.Image = global::Tayninh2011.Properties.Resources.TnSave_28_28;
        }

        private void pbxRefresh_MouseHover(object sender, EventArgs e)
        {
            pbxRefresh.Image = global::Tayninh2011.Properties.Resources.TnRefresh1;
        }

        private void pbxRefresh_MouseLeave(object sender, EventArgs e)
        {
            pbxRefresh.Image = global::Tayninh2011.Properties.Resources.TnRefresh;
        }
        #endregion

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void FrmCash_Load(object sender, EventArgs e)
        {
            this.AddLayer(this._strLayerNames);
            ContexMenuTOC.AddItem(new TnRemoveLayerCmd(), 1, 0, false, esriCommandStyles.esriCommandStyleIconAndText);
            ContexMenuTOC.SetHook(this.axMapControl1);
            //addLayerAuto(this._strLayerNames);
            //ITnMapController mapController = new TnMapController();
            //mapController.AddLayer(this._strLayerNames, RootForm._sdeWorkspace, ref this.axMapControl1, ref this.axTOCControl1);
            //this.axTOCControl1.Validated+= new EventHandler(tocControlHandle);
            
            //MessageBox.Show(mapController.GetLayersName(ref this.axMapControl1)[0]);
        }
        private void tocControlHandle(object sender, EventArgs e)
        {
            MessageBox.Show("ok");
        }
        
        private void button3_Click(object sender, EventArgs e)
        {
            
            
            
            
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //pnlTable.Height=9;
            //FrmMapTools map = new FrmMapTools();
            //map.MdiParent = this;
            
            //map.Show();
            //Form1 form1 = new Form1();
            //form1.Show();
            //MessageBox.Show(mapController.GetLayersName(ref this.axMapControl1).Count.ToString());
            //axMapControl1.Map.DeleteLayer(axMapControl1.Map.get_Layer(0));
            //TnHemFactory hemFact = new TnHemFactory();
            //TnHem hemBuff1 = hemFact.GetHem(EnumLoaiHem.hemBuffer1m, RootForm._sdeWorkspace, RootForm._sdeEnvironment, RootForm._arrUserInfo);
            //string out_featureClass = String.Empty;
            ITnExToolsDataManager toolDataManager = new TnExToolsDataManager();
            //toolDataManager.TnCreateFeatureLayer("tntn_hem_buff_1", "hemChinhLayerBuff1", dieukien, out out_featureClass);
            ITnRelationships re = new TnExToolsDataManager();
            
            IRelationshipClass rc= re.OpenRelationShipClass("pto",RootForm.SdeWorkspace);
            IRelationshipClass duong_kvxa = re.OpenRelationShipClass("duong_kvxa", RootForm.SdeWorkspace);
            IRelationshipClass xa_kvxa = re.OpenRelationShipClass("xa_kvxa", RootForm.SdeWorkspace);
            IRelationshipClass kvxa_datpnnnt = re.OpenRelationShipClass("kvxa_datpnnnt", RootForm.SdeWorkspace);
            ISet s = re.GetRelatedObjectSet(rc, toolDataManager.TnOpenFeatureClassFromSDE(RootForm.SdeWorkspace, "parcel"), "");
            s.Reset();
            IRelClassEnumRowPairs rel = re.GetPairRelatedObjects(rc, toolDataManager.TnOpenFeatureClassFromSDE(RootForm.SdeWorkspace, "parcel"), "");
            IRelClassEnumRowPairs rel_duong_kvx = re.GetPairRelatedObjects(duong_kvxa, toolDataManager.TnOpenFeatureClassFromSDE(RootForm.SdeWorkspace, "tn_duong"), "");
            IRelClassEnumRowPairs rel_kvx_pnnt = re.GetPairRelatedObjects(kvxa_datpnnnt, toolDataManager.OpenTableFromSDE(RootForm.SdeWorkspace, "khuvucxa"), "");
            IRow srcRow = null;
            IRow tarRow = null;
            //rel.Next(out srcRow, out tarRow);
            //rel_duong_kvx.Next(out srcRow, out tarRow);
            rel_kvx_pnnt.Next(out srcRow, out tarRow);
            object o = s.Next();
            while (srcRow != null)
            {
                //ITable table = toolDataManager.OpenTableFromSDE(RootForm.SdeWorkspace,"owner");
                //IFeature ft = null;
                //ICursor cur = null;
                //cur = table.GetRows(o,false);
                //IRow row = cur.NextRow();

                MessageBox.Show(s.Count.ToString() + "--" + srcRow.get_Value(1).ToString() + "--" + tarRow.get_Value(1).ToString());
                rel_kvx_pnnt.Next(out srcRow, out tarRow);
            }
        }

        private void cbxChonLayer_MouseHover(object sender, EventArgs e)
        {
            this.cbxChonLayer.Items.Clear();
            List<String> layers = mapController.GetLayersName(ref this.axMapControl1);
            int len = layers.Count;
            for (int i = 0; i < len; i++)
            {
                this.cbxChonLayer.Items.Add(layers[i]);
            }
            this.cbxChonLayer.SelectedIndex = 0;
        }

        private void mnuTableNames_Click(object sender, EventArgs e)
        {
            //FrmTableNames.UserInfo = this._arrUserInfo;
            
            frmTableName = FrmTableNames.CallMe;
            //RootForm._arrUserInfo = RootForm._arrUserInfo;
            frmTableName.Show();
            
        }

        private void axMapControl1_OnMouseUp(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseUpEvent e)
        {

        }

        private void axMapControl1_OnSelectionChanged(object sender, EventArgs e)
        {
            IEnumFeature featureEnumeration = (IEnumFeature)axMapControl1.Map.FeatureSelection;
            //IFeature pSlectdFtr = featureEnumeration.Next();
            //MessageBox.Show(mapController.SelectAttribute(ref featureEnumeration).Count.ToString());
            Dictionary<string,int> selectedFeature= mapController.SelectAttribute(ref featureEnumeration);

            if (selectedFeature.ContainsKey(table) && this.dgvTable.RowCount!=0)
            {
                dgvTable.ClearSelection();
                for (int i = 0; i < dgvTable.RowCount; i++)
                {
                    if ((int)dgvTable.Rows[i].Cells[dgvTable.Columns["objectid"].Index].Value == selectedFeature[table])
                    {
                        dgvTable.Rows[i].Selected = true;
                        dgvTable.FirstDisplayedScrollingRowIndex=i;
                        //dgvTable.CurrentCell = null;
                        //dgvTable.CurrentCell = dgvTable.Rows[i].Cells[0];
                        //MessageBox.Show(i.ToString()+"--"+dgvTable.Rows[i].Cells[dgvTable.Columns["objectid"].Index].Value.ToString()+"--"+selectedFeature[table].ToString());
                    }
                }
                //dgvTable.Rows[selectedFeature[table]].Selected = true;
                //
            }
            //string playerName = pSlectdFtr.Class.AliasName;
            //IMap map = ((ESRI.ArcGIS.Controls.AxMapControl)sender).Map;
            //IFeatureSelection fl = (IFeatureSelection)map.FeatureSelection.;
            //ILayer l = (ILayer)fl;
            //MessageBox.Show(playerName);
        }
        private string getNameOnly(string fullNameWithDot)
        {
            string[] arrName = fullNameWithDot.Split('.');
            int len = arrName.Length;
            return arrName[len - 1];
        }

        private void button5_Click(object sender, EventArgs e)
        {
            frmAddSdeData = FrmAddSdeData.CallMe;
            frmAddSdeData.Show();
        }

        public void AddLayer(string[] layers)
        {
            mapController.AddLayer(layers, RootForm._sdeWorkspace, ref this.axMapControl1, ref this.axTOCControl1);
        }

        private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {
            IBasicMap map = null;
            ILayer layer = null;
            object obj = null;
            object index = null;
            esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;

            if (e.button == 2)
            {
                //MessageBox.Show("hi");
                axTOCControl1.HitTest(e.x, e.y, ref item, ref map, ref layer, ref obj, ref index);

                ContexMenuTOC.PopupMenu(e.x, e.y, axTOCControl1.hWnd);

                //menu.AddItem("esriControls.ControlsPageZoomWholePageCommand", -1, -1, false, esriCommandStyles.esriCommandStyleIconAndText);
                //menu.AddItem("esriControls.ControlsPageZoomPageToLastExtentBackCommand", -1, -1, true, esriCommandStyles.esriCommandStyleIconAndText);
                //menu.AddItem("esriControls.ControlsPageZoomPageToLastExtentForwardCommand", -1, -1, false, esriCommandStyles.esriCommandStyleIconAndText);

            }
        }

        private void mnuLandPriceStd_Click(object sender, EventArgs e)
        {
            frmLandPrice = FrmLandpriceOnRoad.CallMe;
            frmLandPrice.Show();
        }

        private void tvCachTinh_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag != null)
            {
                //lbxCachtinh.Items.Add(e.Node.Tag.ToString());
                //tbxCachTinh.Text = e.Node.Tag.ToString();
            }
        }

        public void actionComplete(object sender, RunWorkerCompletedEventHandler e)
        {
            this.Cursor = Cursors.Arrow;
            //btnThucHien.Enabled = true;
            pbxThucHien.Enabled = true;
            pbxThucHien.Image = global::Tayninh2011.Properties.Resources.TnCalculator_40_54;
            pbxQuery.Image = global::Tayninh2011.Properties.Resources.query;
            pbxQuery.Enabled = true;
            this.pbrThucHien.Value = 0;
            this.pbrThucHien.Visible = false;

            this.tbxHelpInTasks.Text = "";
            MessageBox.Show("Đã tính xong");
        }

        public void calculating(object sender, ProgressChangedEventArgs e)
        {
            //MessageBox.Show(e.ToString());
            //Thread.Sleep(1000);
            //backgroundWorker1 = new BackgroundWorker();
            //backgroundWorker1.DoWork+=new DoWorkEventHandler(backgroundWorker1_DoWork);
            //backgroundWorker1.RunWorkerAsync(e);
            //while (!excutor.IsFinished)
            //{
            //    if (excutor.Bip == 1)
            //    {
            //        excutor.CalcTool.BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(calculating);
            //        excutor.Bip = 0;
            //    }
            //    //    //MessageBox.Show(excutor.ProgressPercentage.ToString());
            //    //    this.calculating(excutor.ProgressPercentage);

            //    //    //this.pbrThucHien.Value = excutor.ProgressPercentage;

            //}
            this.pbrThucHien.Value = e.ProgressPercentage;
            this.tbxHelpInTasks.Text = excutor.Log;
            this.Cursor = Cursors.AppStarting;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            
            this.pbrThucHien.Value = (int)e.Argument;
            this.tbxHelpInTasks.Text = excutor.Log;
        }

        private void mnuRuleCalc_Click(object sender, EventArgs e)
        {
            FrmRule.CallMe.Show();
        }

        #region Map



        #endregion Map

    }
}
